package com.heima.wemedia.filter;

import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.pojos.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @作者 itcast
 * @创建日期 2021/11/20 15:36
 **/
@WebFilter(value = "wmTokenFilter",urlPatterns = "/*")
@Component
@Slf4j
public class WmTokenFilter  extends GenericFilterBean {
    /**
     * @param servletRequest     请求
     * @param servletResponse    响应
     * @param filterChain        链
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 1. 获取请求对象
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        // 2. 查看请求头是否有userId
        String userId = request.getHeader("userId");
        if(StringUtils.isNotBlank(userId)){
            // 2.1  如果有 就封装一个user信息 存入到 threadlocal变量中
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));
            WmThreadLocalUtils.setUser(wmUser);
            log.info("当前进入微服务的请求  登录用户id为:{}",userId);
        }
        // 3. 放行请求
        filterChain.doFilter(servletRequest,servletResponse);
        // 4. 后置处理  清空threadlocal
        WmThreadLocalUtils.clear(); // 清空登录用户
    }
}
